<template>
  <div>
    <div>
      <a-form class="headerSerch" layout="inline">
        <a-row :gutter="24">
          <a-col :md="5" :sm="24">
            <a-form-item label="单号">
              <a-input v-model="queryParams.sp_no" placeholder="" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="申请人">
              <a-select
                v-model="queryParams.pay_id"
                show-search
                placeholder="Select a person"
                style="width: 200px"
                :options="userList"
                :filter-option="filterOption"
                @change="handleFilterChange"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="24">
            <a-form-item label="报销金额">
              <a-input v-model="queryParams.total_amount" placeholder="" />
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="24">
            <a-form-item label="申报日期">
              <a-date-picker v-model="queryParams.declare_date" placeholder="" />
            </a-form-item>
          </a-col>
          <a-col :md="3" :sm="24">
            <a-button v-action:query @click="search" type="primary">查询</a-button>
            <a-button v-action:query @click="reset" type="default">重置</a-button>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="6" :sm="24">
            <a-button
              v-action:add
              style="float: left; margin-top:10px ;"
              @click="showModal()"
              type="primary"
            >新增</a-button
            >
          </a-col>
        </a-row>
      </a-form>

      <a-table
        rowKey="id"
        :columns="columns"
        :data-source="reimbursementList"
        @expandedRowsChange="expandedRowsChange"
        class="components-table-demo-nested"
        :pagination="false"
        :loading="loading"
      >
        <a slot="status" slot-scope="text">
          <a-tag v-if="text == 0" color="#2db7f5">待审核</a-tag>
          <a-tag v-if="text == 1" color="#87d068">已审核</a-tag>
        </a>
        <a slot="operation" slot-scope="text,record">
          <a-button v-action:update @click="showModal(record)" type="primary">编辑</a-button>
          <a-popconfirm
            title="Are you sure delete this record?"
            ok-text="确定"
            cancel-text="取消"
            @confirm="removeReimbursement(record)"
          >
            <a-button v-action:delete type="danger">删除</a-button>
          </a-popconfirm>
        </a>

        <a-table
          slot="expandedRowRender"
          slot-scope="record"
          rowKey="id"
          :columns="innerColumns"
          :data-source="record.reimbursement_items"
          :pagination="false"
        >
        </a-table>

        <template slot="total_amount" slot-scope="text">
          ¥{{ text }}
        </template>
        <template slot="footer">
          <div class="table-footer">
            <span>小计：</span>
            <span class="total-amount">¥{{ getTotalAmount }}</span>
          </div>
          <div class="table-footer">
            <span>总计：</span>
            <span class="total-amount">¥{{ allRecordtotalAmount }}</span>
          </div>
        </template>
      </a-table>
      <a-pagination
        v-model="queryParams.page"
        :page-size-options="pageSizeOptions"
        :total="total"
        show-size-changer
        :page-size="queryParams.pageSize"
        @showSizeChange="onShowSizeChange"
        @change="changePage"
        class="pagination"
        :show-total="(total, range) => `共${total}条`"
      >
        <template slot="buildOptionText" slot-scope="props">
          <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
        </template>
      </a-pagination>

      <a-modal
        :visible="visible"
        :width="'80%'"
        :title="`${current ? '修改报销单' : '新增报销单'}`"
        okText="确认并提交"
        cancelText="取消"
        @cancel="handleCancel"
        @ok="handleCreateReimbursement"
      >
        <a-form
          layout="horizontal"
          :form="form"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-row type="flex" justify="space-around">
            <a-col :span="6">
              <a-form-item label="申请人">
                <a-select
                  show-search
                  :filter-option="filterOption"
                  v-decorator="[
                    'pay_id',
                    {
                      rules: [{ required: true, message: 'Please select 申请人' }],
                    },
                  ]"
                  placeholder="请选择申请人"
                >
                  <a-select-option v-for="item in userList" :key="item.value" :value="item.value">
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="报销总额">
                <span class="ant-form-text">
                  $
                </span>
                <a-input-number v-model="totalAmount" disabled style="width: 80%;"/>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="申请时间">
                <a-date-picker
                  v-decorator="[
                    'declare_date',
                    {
                      initialValue: getCurrentDate(),
                      rules: [{ required: true, message: 'Please input 申请时间' }],
                    },
                  ]"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="备注">
                <a-input type="textarea" v-decorator="['remark', { initialValue: 'remark' }]" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="24" v-if="!current" v-for="(item, index) in reimbursementItemList" :key="item.guid">
            <a-col :span="4">
              <a-form-item label="项目">
                <a-input
                  v-decorator="[
                    `project_name_${item.guid}`,
                    { rules: [{ required: true, message: '名称不能为空' }], initialValue: '' },
                  ]"
                  @change="
                    (e) => {
                      item.project_name = e.target.value;
                    }
                  "
                />
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item label="不含税金额">
                <a-input
                  v-decorator="[
                    `no_tax_amount_${item.guid}`,
                    { rules: [{ required: true, message: 'Please input' }], initialValue: 0 },
                  ]"
                  @change="
                    (e) => {
                      handleAddAmountChange(e, item, 'no_tax_amount');
                    }
                  "
                />
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item label="税额">
                <a-input
                  v-decorator="[
                    `tax_amount_${item.guid}`,
                    { rules: [{ required: true, message: 'Please input' }], initialValue: 0 },
                  ]"
                  @change="
                    (e) => {
                      handleAddAmountChange(e, item, 'tax_amount');
                    }
                  "
                />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="发生时间">
                <a-date-picker
                  style="width: 100%"
                  v-decorator="[
                    `occurrence_date${item.guid}`,
                    {
                      initialValue: getCurrentDate(),
                      rules: [{ required: true, message: 'Please input payid' }],
                    },
                  ]"
                />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="备注">
                <a-input
                  v-decorator="[
                    `remark_${item.guid}`,
                    // { rules: [{ required: true, message: '名称不能为空' }] },
                  ]"
                  @change="
                    (e) => {
                      item.remark = e.target.value;
                    }
                  "
                />
              </a-form-item>
            </a-col>
            <a-col :span="2">
              <a-form-item>
                <a-icon v-if="index >= 1" type="minus-circle-o" @click="addRemoveItem(index)" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item v-if="!current" v-bind="formItemLayoutWithOutLabel">
            <a-button type="dashed" style="width: 60%" @click="addItem()">
              <a-icon type="plus" /> 新增报销条目
            </a-button>
          </a-form-item>
          <a-row v-if="current">
            <div class="add-item-wrapper">
              <a-button type="dashed" style="width: 60%" @click="updateAddItem()">
                <a-icon type="plus" /> 新增报销条目
              </a-button>
            </div>
            <a-table
              :pagination="false"
              :columns="modalColumns"
              :data-source="reimbursementItemList"
              rowKey="id"
            >
              <template
                v-for="col in ['project_name', 'no_tax_amount', 'tax_amount']"
                :slot="col"
                slot-scope="text, record"
              >
                <template v-if="record.editable">
                  <a-input
                    :key="col"
                    style="margin: -5px 0"
                    :value="text"
                    @change="(e) => handleChange(e.target.value, record.id, col)"
                  />
                </template>
                <template v-else>
                  {{ text }}
                </template>
              </template>
              <template slot="operation" slot-scope="text, record">
                <div class="editable-row-operations">
                  <span v-if="record.editable">
                    <a @click="() => saveItem(record.id)">保存</a>
                    <a-popconfirm title="Sure to cancel?" @confirm="() => cancelEdit(record.id)">
                      <a>取消</a>
                    </a-popconfirm>
                  </span>
                  <span v-else>
                    <a-button
                      type="primary"
                      :disabled="editingKey !== ''"
                      @click="() => editItem(record.id)"
                    >编辑</a-button
                    >
                    <a-button
                      type="danger"
                      :disabled="editingKey !== ''"
                      @click="() => removeItem(record.id)"
                    >删除</a-button
                    >
                  </span>
                </div>
              </template>
            </a-table>
          </a-row>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>

<script>

import request from '@/utils/request'
import { getFormatDate, isNotEmptyList } from '@/utils/util'
// import { ref } from 'vue'

const innerColumns = [
  { title: 'id', dataIndex: 'id', key: 'id' },
  { title: '报销项目', dataIndex: 'project_name', key: 'project_name' },
  { title: '报销金额', dataIndex: 'amount', key: 'amount' },
  { title: '不含税金额', dataIndex: 'no_tax_amount', key: 'no_tax_amount' },
  { title: '税额', dataIndex: 'tax_amount', key: 'tax_amount' },
  {
    title: '发生日期',
    dataIndex: 'occurrence_date',
    key: 'occurrence_date',
    customRender: (text, record) => {
      return getFormatDate(text, 'YYYY-MM-DD')
    }
  }
]

const modalColumns = [
  { title: 'id', dataIndex: 'id', key: 'id', scopedSlots: { customRender: 'id' } },
  {
    title: '报销项目',
    dataIndex: 'project_name',
    key: 'project_name',
    scopedSlots: { customRender: 'project_name' }
  },
  {
    title: '报销金额',
    dataIndex: 'amount',
    key: 'amount',
    scopedSlots: { customRender: 'amount' }
  },
  {
    title: '不含税金额',
    dataIndex: 'no_tax_amount',
    key: 'no_tax_amount',
    scopedSlots: { customRender: 'no_tax_amount' }
  },
  {
    title: '税额',
    dataIndex: 'tax_amount',
    key: 'tax_amount',
    scopedSlots: { customRender: 'tax_amount' }
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]

export default {
  name: 'AntdDemo',
  components: {

  },
  data () {
    const columns = [
      { title: '报销单号', dataIndex: 'sp_no', key: 'sp_no' },
      { title: '申请人', dataIndex: 'pay_user.username', key: 'pay_id' },
      {
        title: '报销金额',
        dataIndex: 'total_amount',
        key: 'total_amount',
        scopedSlots: { customRender: 'total_amount' }
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        customRender: (text, record) => {
          return (
            <a-tooltip placement="top">
              <template slot="title">
                <span>{text}</span>
              </template>
              <span>{text}</span>
            </a-tooltip>
          )
        }
      },
      {
        title: '申请日期',
        dataIndex: 'declare_date',
        key: 'declare_date',
        customRender: (text, record) => {
          return getFormatDate(text, 'YYYY-MM-DD')
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        scopedSlots: { customRender: 'status' }
      },
      { title: '操作', key: 'operation', scopedSlots: { customRender: 'operation' } }
    ]
    return {
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 20, offset: 4 }
        }
      },

      pageSizeOptions: ['2', '5', '10', '20'],
      queryParams: {
        page: 1,
        pageSize: 10
      },
      editingKey: '',
      total: 0,
      form: this.$form.createForm(this, { name: 'reimbursement' }),
      visible: false,
      columns,
      totalAmount: 0,
      allRecordtotalAmount: 0,
      loading: false,
      current: undefined,
      innerColumns,
      modalColumns,
      expandedRowKeys: [],
      reimbursementList: [],
      reimbursementItemList: [],
      cacheData: [],
      userList: []
    }
  },

  beforeCreate () {
    // 创建表单
    this.form = this.$form.createForm(this, { name: 'reimbursement' })
    this.form.getFieldDecorator('keys', { initialValue: [], preserve: true })
  },

  watch: {
    reimbursementItemList (newList, oldList) {
      let totalAmount = 0
      if (newList.length > 0) {
        newList.map((item) => {
          totalAmount = totalAmount + parseFloat(item.no_tax_amount) + parseFloat(item.tax_amount)
        })
        this.totalAmount = totalAmount
      }
    }
  },
  created () {
    this.getReimbursementList(this.queryParams)
    this.getUserList()
  },

  methods: {
    handleFilterChange (value) {
      console.log(`selected ${value}`)
      this.queryParams.pay_id = value
    },

    filterOption (input, option) {
      // 自定义搜索逻辑，根据关键词匹配文本
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },

    async getUserList () {
      const response = await request.get('/user/', {
        params: {
          page: 1,
          limit: 999
        }
      })
      if (isNotEmptyList(response.data.data)) {
        response.data.data.map((item) => {
          this.userList.push({
            value: item.id,
            label: item.username
          })
        })
      }
    },

    search () {
      this.queryParams.page = 1
      this.getReimbursementList(this.queryParams)
    },

    reset () {
      this.queryParams = {
        page: 1,
        pageSize: this.queryParams.pageSize
      }
      this.getReimbursementList(this.queryParams)
    },

    changePage (current, pageSize) {
      this.queryParams.page = current
      this.getReimbursementList(this.queryParams)
    },

    onShowSizeChange (current, pageSize) {
      this.queryParams.pageSize = pageSize
      this.getReimbursementList(this.queryParams)
    },

    addItem () {
      var itemObj = {
        guid: this.guid(),
        project_name: '',
        no_tax_amount: 0,
        occurrence_date: getFormatDate(new Date(), 'YYYY-MM-DD'),
        tax_amount: 0,
        remark: ''
      }
      this.reimbursementItemList.push(itemObj)
    },

    updateAddItem () {
      if (this.editingKey !== '') {
        this.$message.warning('请先保存当前选项')
        return
      }
      // 创建一个新的空对象
      const newItem = {
        id: -1, // 临时ID，用于前端标识
        project_name: '',
        no_tax_amount: 0,
        tax_amount: 0,
        amount: 0,
        occurrence_date: this.getCurrentDate(),
        remark: '',
        editable: true // 新增的项默认为可编辑状态
      }

      // 将新对象添加到列表中
      this.reimbursementItemList = [...this.reimbursementItemList, newItem]
      // 设置当前编辑的key为新项的id
      this.editingKey = newItem.id
    },

    guid () {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        var r = Math.random() * 16 || 0
        const v = c === 'x' ? r : r & 0x3 || 0x8
        return v.toString(16)
      })
    },

    addRemoveItem (index) {
      this.reimbursementItemList.splice(index, 1)
    },

    async getReimbursementList (queryParams) {
      this.loading = true
      if (queryParams.declare_date) {
        queryParams.declare_date = getFormatDate(queryParams.declare_date, 'YYYY-MM-DD')
      }
      const response = await request.get(`reimbursement/list/`, {
        params: queryParams
      })
      if (isNotEmptyList(response.data.data)) {
        this.reimbursementList = response.data.data
        this.total = response.data.total
        this.allRecordtotalAmount = response.data.total_amount
        this.loading = false
      }
    },

    async getReimbursementById (id) {
      const response = await request.get(`reimbursement/list/${id}/`)
      if (response) {
        this.current = response.data.data
        this.totalAmount = response.data.data.total_amount
        this.reimbursementItemList = response.data.data.reimbursement_items
      }
    },

    async updateReimbursementItem (paramas) {
      const response = await request.patch(`reimbursement/item_list/${paramas.id}/`, {
        ...paramas
      })

      return response
    },

    getCurrentDate () {
      return getFormatDate(new Date(), 'YYYY-MM-DD')
    },

    async addReimbursement (paramas) {
      const response = await request.post('reimbursement/list/', {
        ...paramas
      })
      if (response) {
        this.getReimbursementList(this.queryParams)
      }
    },

    async updateReimbursement (paramas, id) {
      const response = await request.patch(`reimbursement/list/${id}/`, {
        ...paramas
      })
      if (response) {
        this.getReimbursementList(this.queryParams)
      }
    },

    expandedRowsChange (expanded, b, c, d) {
      if (expanded) {
        // console.log('expanded', expanded, b,c,d);
      }
    },

    // 新增时，监听不到 reimbursementItemList 变化，这里再额外处理一下
    handleAddAmountChange (e, item, str) {
      if (str === 'tax_amount') {
        item.tax_amount = e.target.value
      } else if (str === 'no_tax_amount') {
        item.no_tax_amount = e.target.value
      }

      let totalAmount = 0
      this.reimbursementItemList.map((item) => {
        totalAmount = totalAmount + parseFloat(item.no_tax_amount) + parseFloat(item.tax_amount)
      })
      this.totalAmount = totalAmount
    },

    async removeReimbursement (record) {
      const response = await request.delete(`reimbursement/list/${record.id}`)
      if (response.code === 2000) {
        this.$message.success('删除成功')
        this.getReimbursementList(this.queryParams)
      }
    },
    async removeReimbursementItem (itemId) {
      const response = await request.delete(`reimbursement/item_list/${itemId}/`)
      if (response.code === 2000) {
        this.$message.success('删除成功')
        this.getReimbursementById(this.current.id)
        this.getReimbursementList(this.queryParams)
      }
      return response
    },

    showModal (record) {
      const form = this.form
      if (record) {
        this.current = record
        this.totalAmount = record.total_amount
        this.reimbursementItemList = record.reimbursement_items
        this.cacheData = record.reimbursement_items.map((item) => ({ ...item }))
        this.$nextTick(() => {
          form.setFieldsValue({
            pay_id: record.pay_user.id,
            declare_date: getFormatDate(record.declare_date, 'YYYY-MM-DD'),
            remark: record.remark
          })
        })
      }
      this.visible = true
    },

    handleCreateReimbursement () {
      // const form = this.$refs.collectionForm.form;
      const form = this.form
      // values = form.getFieldsValue()
      // console.log('valuesvaluesvalues',values)
      form.validateFields((err, values) => {
        if (err) {
          return
        }

        values.declare_date = getFormatDate(values.declare_date, 'YYYY-MM-DD')
        const reimbursementItemList = this.reimbursementItemList
        for (const item of reimbursementItemList) {
          delete item.guid
        }
        values.reimbursement_items = this.reimbursementItemList

        let response
        if (this.current && this.current.id) {
          const id = this.current.id
          response = this.updateReimbursement(values, id)
          this.$message.success('修改成功')
        } else {
          response = this.addReimbursement(values)
          this.$message.success('添加成功')
        }

        if (response) {
          form.resetFields()
          this.visible = false
          this.current = undefined
        }
      })
    },

    handleCancel () {
      this.form.resetFields()
      this.visible = false
      this.current = undefined
      this.totalAmount = 0
      this.reimbursementItemList = []
    },

    removeItem (itemId) {
      if (this.reimbursementItemList.length === 1) {
        this.$message.info('至少保留一条报销明细！！！')
        return
      }

      const newData = [...this.reimbursementItemList]
      const filterItemList = newData.filter((item) => itemId !== item.id)
      this.reimbursementItemList = filterItemList
      this.removeReimbursementItem(itemId)
    },

    async saveItem (id) {
      const newData = [...this.reimbursementItemList]
      const target = newData.find((item) => id === item.id)
      if (target) {
        // 如果是新增的项（id是临时生成的）
        if (typeof id === 'number' && id === -1) {
          // 调用新增API
          const response = await request.post('reimbursement/item_list/', {
            reimbursement_id: this.current.id,
            project_name: target.project_name,
            no_tax_amount: target.no_tax_amount,
            tax_amount: target.tax_amount,
            amount: parseFloat(target.no_tax_amount) + parseFloat(target.tax_amount),
            occurrence_date: this.getCurrentDate()
          })

          if (response.code === 2000) {
            this.$message.success('添加成功')
            this.getReimbursementById(this.current.id)
            this.getReimbursementList(this.queryParams)
          }
        } else {
          // 原有的更新逻辑
          delete target.editable
          this.reimbursementItemList = newData
          Object.assign(this.cacheData.find((item) => id === item.id), target)
          const response = await this.updateReimbursementItem(target)
          if (response.code === 2000) {
            this.$message.success('更新成功')
            this.getReimbursementById(this.current.id)
            this.getReimbursementList(this.queryParams)
          }
        }
        this.editingKey = ''
      }
    },

    editItem (id) {
      const newData = [...this.reimbursementItemList]
      const target = newData.find((item) => id === item.id)
      this.editingKey = id
      if (target) {
        target.editable = true
        this.reimbursementItemList = newData
      }
    },

    handleChange (value, id, column) {
      const newData = [...this.reimbursementItemList]
      const target = newData.find((item) => id === item.id)
      if (target) {
        target[column] = value
        target.amount = parseFloat(target.no_tax_amount) + parseFloat(target.tax_amount)

        this.reimbursementItemList = newData
      }
    },

    cancelEdit (id) {
      const newData = [...this.reimbursementItemList]
      const target = newData.find((item) => id === item.id)
      this.editingKey = ''

      if (id === -1) {
        // 如果是新增的项，直接从列表中移除
        this.reimbursementItemList = newData.filter(item => item.id !== -1)
      } else {
        // 将缓存中的数据还原
        if (target) {
          Object.assign(
            target,
            this.cacheData.find((item) => id === item.id)
          )
          delete target.editable
          this.reimbursementItemList = newData
        }
      }
    }
  },
  computed: {
    getTotalAmount () {
      return this.reimbursementList.reduce((sum, item) => {
        return sum + parseFloat(item.total_amount || 0)
      }, 0).toFixed(2)
    }
  }
}
</script>

<style>
.headerSerch {
  padding: 20px;
}
.pagination {
  float: right;
  padding: 40px;
}

.components-table-demo-nested {
  padding: 20px;
}

.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #777;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
.add-item-wrapper {
  width:100%;
  margin-bottom :10px;
  text-align: center;
}

.table-footer {
  text-align: left;
  padding-right: 20px;
}

.total-amount {
  font-weight: bold;
  font-size: 16px;
  color: #1890ff;
}
</style>
